import {login, logout, getInfo, getMenuList} from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    router:undefined,
    info:''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROUTER: (state, router) => {
    state.router = router
  },
  SET_INFO: (state, info) => {
    state.info = info
  }
}

const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return (resolve) => require([`@/views${view}`], resolve)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views${view}`)
  }
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // username.trim 删除前面和后面的空格
      login({ username: username.trim(), password: password }).then(res => {
        let data = res.message
        // 将token值同步到Vuex
        commit('SET_TOKEN', data)
        // 设置公共的token值
        setToken(data)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  getRouter({commit }){
    return new Promise(( resolve, reject ) =>  {
      getMenuList().then( res =>{

        let data = res.data

        let routers = []

        data.forEach( d =>{

          routers.push({
            path:'/staging' + d.path,
            name: d.name,
            component: loadView( d.url ),
            meta:{
              label:d.label,icon:d.icon
            }
          })
        })

        commit('SET_ROUTER', routers )
        resolve(routers)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 根据token值获取用户的基本信息
      // code:状态码,data:用户基本信息
      getInfo(state.token).then(res => {
        let data = res.data
        // data中没有数据
        if (!data) {
          return reject('验证失败,请重新登录。')
        }

        const { name, avatar } = data
        // 将 用户名 同步到Vuex
        commit('SET_NAME', name)
        commit('SET_INFO', data)
        // 将 用户头像 同步到Vuex
        commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 用户退出
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // 必须先删除令牌
        resetRouter()
        // 将 用户信息 同步到Vuex
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 删除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // 删除令牌(必须先删除令牌)
      commit('RESET_STATE')
      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

